package com.millstein.realtime.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.millstein.realtime.app.base.BaseAppV1;
import com.millstein.realtime.app.func.DimAsyncFunction;
import com.millstein.realtime.bean.TradeProvinceOrderWindow;
import com.millstein.realtime.common.Constants;
import com.millstein.realtime.util.CommonUtil;
import com.millstein.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.*;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author tsing
 * @Date 2024-10-31 16:38
 */
public class Dws_10_TradeProvinceOrderWindow extends BaseAppV1 {

    public static void main(String[] args) {
        new Dws_10_TradeProvinceOrderWindow().init(
                8010,
                1,
                "Dws_10_TradeProvinceOrderWindow",
                Constants.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }

    /**
     * 具体数据处理的逻辑，由子类编写
     *
     * @param env          执行环境对象
     * @param streamSource 待处理的数据流
     */
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> streamSource) {
        // 1.去重
        SingleOutputStreamOperator<TradeProvinceOrderWindow> dataStream = removeDuplicationData(streamSource);
        // 2.窗口计算
        SingleOutputStreamOperator<TradeProvinceOrderWindow> aggregateStream = windowAndAgg(dataStream);
        // 3.补齐维度
        SingleOutputStreamOperator<TradeProvinceOrderWindow> resultStream = supplementDim(aggregateStream);resultStream.print();
        // 4.写到doris中
        writeToDoris(resultStream);
    }

    /**
     * 将数据流中的数据去重
     * @param streamSource 待去重的数据流
     * @return
     */
    private SingleOutputStreamOperator<TradeProvinceOrderWindow> removeDuplicationData(
            DataStreamSource<String> streamSource
    ) {
        return streamSource
                .map(new MapFunction<String, JSONObject>() {
                    @Override
                    public JSONObject map(String value) throws Exception {
                        return JSONObject.parseObject(value);
                    }
                })
                .keyBy(item -> item.getString("order_id"))
                .process(new KeyedProcessFunction<String, JSONObject, TradeProvinceOrderWindow>() {

                    MapState<String, JSONObject> state;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        state = getRuntimeContext().getMapState(
                                new MapStateDescriptor<>("ts-state", String.class, JSONObject.class)
                        );
                    }

                    @Override
                    public void processElement(
                            JSONObject value,
                            Context ctx,
                            Collector<TradeProvinceOrderWindow> out
                    ) throws Exception {
                        String detailId = value.getString("id");
                        if (state.values().spliterator().estimateSize() == 0) {
                            // 本订单对应的状态为空，说明这个订单对应的订单详情尚未到达
                            // 此时订单中第一条订单详情的数据到达，需要开启定时器
                            ctx.timerService().registerProcessingTimeTimer(
                                    ctx.timerService().currentProcessingTime() + 5 * 1000
                            );
                            // 说明这个订单详情是第一次出现，直接将订单详情放入状态中即可
                            state.put(detailId, value);
                        } else {
                            // 本订单对应的状态不为空，说明这个订单已经有订单详情到达
                            JSONObject lastRecord = state.get(detailId);
                            if (lastRecord == null) {
                                // 说明这个订单的订单详情是第一次出现，但这个订单的其他的订单详情已经出现过
                                state.put(detailId, value);
                            }
                            // 如果不是null，那么说明这个订单详情已经出现过，是重复数据，所以丢弃不处理
                        }
                    }

                    @Override
                    public void onTimer(long timestamp,
                                        OnTimerContext ctx,
                                        Collector<TradeProvinceOrderWindow> out
                    ) throws Exception {
                        BigDecimal orderAmount = BigDecimal.ZERO;
                        String provinceId = null;
                        Long ts = null;
                        for (JSONObject record : state.values()) {
                            if (provinceId == null) {
                                provinceId = record.getString("province_id");
                            }
                            if (ts == null) {
                                ts = record.getLong("od_ts") * 1000;
                            }
                            orderAmount = orderAmount.add(record.getBigDecimal("split_total_amount"));
                        }
                        out.collect(TradeProvinceOrderWindow.builder()
                                .provinceId(provinceId)
                                .orderCount(1L)
                                .orderAmount(orderAmount)
                                .ts(ts)
                                .build());
                        state.clear();
                    }
                });
    }

    /**
     * 窗口聚合计算
     * @param orderStream 待窗口聚合计算的数据流
     * @return
     */
    private SingleOutputStreamOperator<TradeProvinceOrderWindow> windowAndAgg(
            SingleOutputStreamOperator<TradeProvinceOrderWindow> orderStream
    ) {
        return orderStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<TradeProvinceOrderWindow>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((element, timestamp) -> element.getTs())
                )
                .keyBy(TradeProvinceOrderWindow::getProvinceId)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<TradeProvinceOrderWindow>() {
                            @Override
                            public TradeProvinceOrderWindow reduce(
                                    TradeProvinceOrderWindow bean1,
                                    TradeProvinceOrderWindow bean2
                            ) throws Exception {
                                bean1.setOrderCount(bean1.getOrderCount() + bean2.getOrderCount());
                                bean1.setOrderAmount(bean1.getOrderAmount().add(bean2.getOrderAmount()));
                                return bean1;
                            }
                        },
                        new ProcessWindowFunction<TradeProvinceOrderWindow, TradeProvinceOrderWindow, String, TimeWindow>() {
                            @Override
                            public void process(
                                    String key,
                                    Context context,
                                    Iterable<TradeProvinceOrderWindow> elements,
                                    Collector<TradeProvinceOrderWindow> out
                            ) throws Exception {
                                TradeProvinceOrderWindow bean = elements.iterator().next();
                                String startTime = CommonUtil.formatTime(context.window().getStart());
                                String endTime = CommonUtil.formatTime(context.window().getEnd());
                                String curDate = startTime.substring(0, 10);
                                bean.setStt(startTime);
                                bean.setEdt(endTime);
                                bean.setCurDate(curDate);
                                out.collect(bean);
                            }
                        }
                );
    }

    /**
     * 补齐维度信息
     * @param aggregateStream 聚合后的数据流
     * @return
     */
    private SingleOutputStreamOperator<TradeProvinceOrderWindow> supplementDim(
            SingleOutputStreamOperator<TradeProvinceOrderWindow> aggregateStream
    ) {
        return AsyncDataStream.unorderedWait(
                aggregateStream,
                new DimAsyncFunction<TradeProvinceOrderWindow>() {
                    @Override
                    protected String getTableName() {
                        return "dim_base_province";
                    }

                    @Override
                    protected String getId(TradeProvinceOrderWindow input) {
                        return input.getProvinceId();
                    }

                    @Override
                    protected void supplementDim(TradeProvinceOrderWindow bean, JSONObject dim) {
                        bean.setProvinceName(dim.getString("NAME"));
                    }
                },
                30,
                TimeUnit.SECONDS,
                50
        );
    }

    /**
     * 将结果数据写入doris中
     * @param resultStream 处理完的数据流
     */
    private void writeToDoris(SingleOutputStreamOperator<TradeProvinceOrderWindow> resultStream) {
        resultStream
                .map(item -> {
                    SerializeConfig config = new SerializeConfig();
                    config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
                    return JSONObject.toJSONString(item, config);
                })
                .addSink(FlinkSinkUtil.getDorisSink("gmall.dws_trade_province_order_window"));
    }
}
